import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:landlore/consts.dart';
import 'package:landlore/screens/recordDetailScreen.dart';
import 'package:landlore/screens/reviewScreen.dart';

import '../customWidget/yearMonthCupPicker.dart';
import '../dbUtil/databaseHelper.dart';
import '../model/orderVO.dart';

class RecordScreen extends StatefulWidget {
  //当前选中的 年/月 ,初始化为当前时间
  int currentYear;
  int currentMonth;

  RecordScreen(
      {super.key, required this.currentYear, required this.currentMonth});

  @override
  State<RecordScreen> createState() => _RecordScreenState();
}

class _RecordScreenState extends State<RecordScreen> {
  //缓存区数据,确定后才使用
  late int currentYear;
  late int currentMonth;
  late int currentYearTemp;
  late int currentMonthTemp;
  String keyword = '';

  List<OrderVO> roomList = [];

  bool _sortAscending = true;
  int _sortColumnIndex = 0;
  List<DataRow> _rows = [];

  @override
  void initState() {
    currentYear = widget.currentYear;
    currentMonth = widget.currentMonth;
    _getRoomList();

    // TODO: implement initState
    super.initState();
  }

  @override
  dispose() {
    super.dispose();
  }

  _getRoomList() async {
    DatabaseHelper dbHelper = DatabaseHelper.instance;
    List<OrderVO> resultData = await dbHelper.getOrderFroRecordScreen(
        currentYear, currentMonth, keyword);
    setState(() {
      roomList = resultData;
    });

    //统计合计数据
    int eleSum = 0;
    int waterSum = 0;
    double eleChargeSum = 0;
    double waterChargeSum = 0;
    double rentSum = 0;
    double othersSum = 0;
    for (var element in roomList) {
      element.electricityCharge =
          double.parse(element.electricityCharge!.toString());
      element.waterCharge =
          double.parse(element.waterCharge!.toString());

      eleSum += element.electricityAmountResult!;
      waterSum += element.waterAmountResult!;
      eleChargeSum += element.electricityCharge!;
      waterChargeSum += element.waterCharge!;
      rentSum += element.rent!;
      othersSum += element.otherCharge!;
    }
    //勾选框初始化
    // _isSelected = List.generate(roomList.length, (index) => false);
    //表格数据初始化
    _rows = List<DataRow>.generate(
        roomList.length,
        (index) => DataRow(
                //点击单行事件,跳转订单详情
                onSelectChanged: (isSelected) {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) =>
                              RecordDetailScreen(orderOV: roomList[index])));
                },
                cells: [
                  DataCell(
                    Center(child: Text(roomList[index].roomNum??'-')),
                  ),
                  DataCell(
                    Center(child: Text(roomList[index].contact??'-')),
                  ),
                  DataCell(
                    Center(
                        child: Text(
                            '${roomList[index].createDate!.year.toString()}年.${roomList[index].createDate!.month.toString()}月')),
                  ),
                  DataCell(
                    Center(
                        child: Text(roomList[index]
                            .electricityAmountResult
                            .toString())),
                  ),
                  DataCell(
                    Center(
                        child:
                            Text(roomList[index].waterAmountResult.toString())),
                  ),
                  DataCell(
                    Center(
                        child:
                            Text(roomList[index].electricityCharge!.toStringAsFixed(1))),
                  ),
                  DataCell(
                    Center(child: Text(roomList[index].waterCharge!.toStringAsFixed(1))),
                  ),
                  DataCell(
                    Center(
                        child:
                        Text(roomList[index].electricityAmount.toString())),
                  ),
                  DataCell(
                    Center(child: Text(roomList[index].waterAmount.toString())),
                  ),
                  DataCell(
                    Center(child: Text(roomList[index].rent.toString())),
                  ),
                  DataCell(
                    Center(child: Text(roomList[index].otherCharge.toString())),
                  ),
                ]));
    //追加合计栏
    _rows.add(DataRow(cells: [
      const DataCell(
        Center(child: Text('合计')),
      ),
      const DataCell(
        Center(child: Text('-')),
      ),
      const DataCell(
        Center(child: Text('-')),
      ),
      DataCell(
        Center(child: Text(eleSum.toString())),
      ),
      DataCell(
        Center(child: Text(waterSum.toString())),
      ),
      DataCell(
        Center(child: Text(eleChargeSum.toStringAsFixed(1))),
      ),
      DataCell(
        Center(child: Text(waterChargeSum.toStringAsFixed(1))),
      ),
      const DataCell(
        Center(child: Text('-')),
      ),
      const DataCell(
        Center(child: Text('-')),
      ),
      DataCell(
        Center(child: Text(rentSum.toString())),
      ),
      DataCell(
        Center(child: Text(othersSum.toString())),
      ),
    ]));
  }

  void _sortData() {
    _rows.sort((a, b) {
      if (_sortAscending) {
        return ((a.cells[_sortColumnIndex].child as Center))
            .child
            .toString()
            .compareTo(
                ((b.cells[_sortColumnIndex].child as Center)).child.toString());
      } else {
        return ((b.cells[_sortColumnIndex].child as Center))
            .child
            .toString()
            .compareTo(
                ((a.cells[_sortColumnIndex].child as Center)).child.toString());
      }
    });
  }

  void _sortDataNum() {
    _rows.sort((a, b) {
      int intA = int.parse(
          ((a.cells[_sortColumnIndex].child as Center).child as Text).data ??
              '0');
      int intB = int.parse(
          ((b.cells[_sortColumnIndex].child as Center).child as Text).data ??
              '0');
      if (_sortAscending) {
        return intA.compareTo(intB);
      } else {
        return intB.compareTo(intA);
      }
    });
  }

  void _sortDataDouble() {
    _rows.sort((a, b) {
      double doubleA = double.parse(
          ((a.cells[_sortColumnIndex].child as Center).child as Text).data ??
              '0.0');
      double doubleB = double.parse(
          ((b.cells[_sortColumnIndex].child as Center).child as Text).data ??
              '0.0');
      if (_sortAscending) {
        return doubleA.compareTo(doubleB);
      } else {
        return doubleB.compareTo(doubleA);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      ///设置文字大小不随系统设置改变
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: const Color(0xffe9c46a),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 35.sp,
              color: Colors.black,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          actions: [
            CupertinoButton(
                // color: Colors.blueAccent,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Icon(Icons.assessment, color: Colors.black54, size: 29.sp),
                    Text(
                      '数据统计',
                      style: TextStyle(fontSize: 16.sp, color: Colors.black54),
                    ),
                  ],
                ),
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ReviewScreen(
                                widget.currentYear,
                                widget.currentMonth,
                              )));
                })
          ],
        ),
        body: Container(
          decoration: BoxDecoration(
              // color: const Color(0xfff4a261),
              image: DecorationImage(
                  image: const AssetImage('assets/images/crossword.png'),
                  repeat: ImageRepeat.repeat,
                  colorFilter: ColorFilter.mode(
                      Colors.black.withOpacity(0.3), BlendMode.srcIn))),
          child: Column(
            children: [
              Padding(
                padding: EdgeInsets.all(8.0.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton(
                        style: ButtonStyle(
                            backgroundColor:
                                MaterialStatePropertyAll(Colors.orange[200])),
                        onPressed: () {
                          showModalBottomSheet(
                              context: context,
                              builder: (context) {
                                return SizedBox(
                                  height: 350.h,
                                  child: Column(
                                    children: [
                                      Expanded(
                                        child: YearMonthCupPicker(
                                          callback: (value, year, month) {
                                            // selectedDateTemp = value;
                                            currentYearTemp = year;
                                            currentMonthTemp = month;
                                          },
                                          inputYear: currentYear,
                                          inputMonth: currentMonth,
                                        ),
                                      ),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          CupertinoButton(
                                              child: Text(
                                                "确定",
                                                style: TextStyle(
                                                    fontSize: 25.sp,
                                                    backgroundColor:
                                                        Colors.white),
                                              ),
                                              onPressed: () {
                                                setState(() {
                                                  currentYear = currentYearTemp;
                                                  currentMonth =
                                                      currentMonthTemp;
                                                });
                                                _getRoomList();
                                                Navigator.pop(context);
                                              }),
                                          CupertinoButton(
                                              child: Text(
                                                "清空",
                                                style: TextStyle(
                                                    fontSize: 25.sp,
                                                    backgroundColor:
                                                        Colors.white),
                                              ),
                                              onPressed: () {
                                                setState(() {
                                                  //当前月标记为0 ,因为操作年份会导致再次选择时,年份跳到1900年
                                                  currentMonth = 0;
                                                });
                                                _getRoomList();
                                                Navigator.pop(context);
                                              }),
                                        ],
                                      )
                                    ],
                                  ),
                                );
                              });
                        },
                        child: SizedBox(
                          width: 120.w,
                          height: 60.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                currentMonth == 0
                                    ? '-'
                                    : "$currentYear.$currentMonth月",
                                style: TextStyle(
                                    fontSize: 20.sp, color: Colors.black45),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 12.h),
                                child: Icon(
                                  Icons.arrow_drop_down,
                                  size: 20.sp,
                                  color: Colors.black,
                                ),
                              )
                            ],
                          ),
                        )),
                    Container(
                      width: 120.w,
                      height: 60.h,
                      margin: EdgeInsets.only(left: 30.w),
                      child: TextField(
                        onChanged: (value) {
                          keyword = value;
                        },
                        onSubmitted: (value) {
                          keyword = value;
                          _getRoomList();
                        },
                        decoration: InputDecoration(
                          labelText: '搜索',
                          labelStyle:
                              TextStyle(color: Colors.black, fontSize: 20.sp),
                          floatingLabelStyle:
                              const TextStyle(color: Color(0xff45C7B8)),
                        ),
                        style: TextStyle(fontSize: 20.sp),
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                child: Padding(
                  padding: EdgeInsets.all(16.w),
                  child: Theme(
                    data: ThemeData(
                        iconTheme: const IconThemeData(color: Colors.white),
                        scrollbarTheme: ScrollbarThemeData(
                          thickness: MaterialStateProperty.all(5),
                          // thumbVisibility: MaterialStateProperty.all(true),
                          // thumbColor: MaterialStateProperty.all<Color>(Colors.yellow)
                        )),
                    child: DataTable2(
                        //隐藏勾选框,不需要,点击条目显示订单详情
                        showCheckboxColumn: false,
                        //固定第一第二列
                        fixedLeftColumns: 2,
                        // Forcing all scrallbars to be visible, alternatively themes can be used (see above)
                        headingRowColor: MaterialStateColor.resolveWith(
                            (states) => Colors.grey[850]!),
                        headingTextStyle: const TextStyle(color: Colors.white),
                        headingCheckboxTheme: CheckboxThemeData(
                            side: BorderSide(color: Colors.white, width: 2.w)),
                        //checkboxAlignment: Alignment.topLeft,
                        isHorizontalScrollBarVisible: true,
                        isVerticalScrollBarVisible: true,
                        columnSpacing: 0,
                        horizontalMargin: 12,
                        bottomMargin: 10,
                        minWidth: 900.w,
                        sortColumnIndex: _sortColumnIndex,
                        sortAscending: _sortAscending,
                        columns: [
                          DataColumn2(
                            fixedWidth: 65.w,
                            label: const Center(child: Text('房号')),
                            // numeric: true,
                            onSort: (columnIndex, ascending) {
                              setState(() {
                                _sortColumnIndex = columnIndex;
                                _sortAscending = ascending;
                                _sortData();
                              });
                            },
                            // size: ColumnSize.L,
                          ),
                          DataColumn2(
                            fixedWidth: 80.w,
                            label: const Center(child: Text('租户')),
                          ),
                          DataColumn2(
                            fixedWidth: 100.w,
                            label: const Center(child: Text('日期')),
                            // numeric: true,
                            onSort: (columnIndex, ascending) {
                              setState(() {
                                _sortColumnIndex = columnIndex;
                                _sortAscending = ascending;
                                _sortData();
                              });
                            },
                            // size: ColumnSize.L,
                          ),
                          DataColumn2(
                            fixedWidth: 80.w,
                            label: const Center(child: Text('用电量')),
                            onSort: (columnIndex, ascending) {
                              setState(() {
                                _sortColumnIndex = columnIndex;
                                _sortAscending = ascending;
                                _sortDataNum();
                              });
                            },
                            numeric: true,
                          ),
                          DataColumn2(
                            fixedWidth: 80.w,
                            label: const Center(child: Text('用水量')),
                            onSort: (columnIndex, ascending) {
                              setState(() {
                                _sortColumnIndex = columnIndex;
                                _sortAscending = ascending;
                                _sortDataNum();
                              });
                            },
                            numeric: true,
                          ),
                          DataColumn2(
                            fixedWidth: 80.w,
                            label: const Center(child: Text('电费')),
                            onSort: (columnIndex, ascending) {
                              setState(() {
                                _sortColumnIndex = columnIndex;
                                _sortAscending = ascending;
                                _sortDataDouble();
                              });
                            },
                            numeric: true,
                          ),
                          DataColumn2(
                            fixedWidth: 80.w,
                            label: const Center(child: Text('水费')),
                            onSort: (columnIndex, ascending) {
                              setState(() {
                                _sortColumnIndex = columnIndex;
                                _sortAscending = ascending;
                                _sortDataDouble();
                              });
                            },
                            numeric: true,
                          ),
                          DataColumn2(
                            fixedWidth: 80.w,
                            label: Center(child: Text('电表读数')),
                          ),
                          DataColumn2(
                            fixedWidth: 80.w,
                            label: Center(child: Text('水表读数')),
                          ),
                          DataColumn2(
                            label: const Center(child: Text('租金')),
                            onSort: (columnIndex, ascending) {
                              setState(() {
                                _sortColumnIndex = columnIndex;
                                _sortAscending = ascending;
                                _sortDataNum();
                              });
                            },
                            numeric: true,
                          ),
                          DataColumn2(
                            label: const Center(child: Text('附加费')),
                            onSort: (columnIndex, ascending) {
                              setState(() {
                                _sortColumnIndex = columnIndex;
                                _sortAscending = ascending;
                                _sortDataDouble();
                              });
                            },
                            numeric: true,
                          ),
                        ],
                        rows: _rows),
                  ),
                ),
              ),
            ],
          ),
          // child: ListView.builder(
          //   itemCount: roomList.length,
          //   itemBuilder: (context, index) {
          //     int checkedState = roomList[index].state;
          //     return GestureDetector(
          //       onTap: () {
          //         Navigator.push(
          //             context,
          //             MaterialPageRoute(
          //                 builder: (context) =>
          //                     RecordDetailScreen(orderOV: roomList[index])));
          //       },
          //       child: Container(
          //         padding: EdgeInsets.only(left: 50.w, right: 50.w),
          //         child: Card(
          //           color: Colors.white70,
          //           elevation: 10,
          //           margin: EdgeInsets.all(8.w),
          //           child: Container(
          //             padding: EdgeInsets.only(left: 20.w, right: 40.w),
          //             child: Row(
          //               mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //               children: [
          //                 Expanded(
          //                   child: Text(
          //                     roomList[index].roomNum,
          //                     style: Consts.titleText.copyWith(fontSize: 35.sp),
          //                   ),
          //                 ),
          //                 checkedState == 0
          //                     ? const Chip(
          //                         label: Text("未抄表"),
          //                         avatar: Icon(Icons.error_outline),
          //                         backgroundColor: Colors.orange,
          //                         labelStyle: TextStyle(color: Colors.black),
          //                       )
          //                     : checkedState == 1
          //                         ? const Chip(
          //                             label: Text("已抄表"),
          //                             avatar: Icon(Icons.check_circle_outline),
          //                             backgroundColor: Colors.green,
          //                             labelStyle:
          //                                 TextStyle(color: Colors.black),
          //                           )
          //                         : const Chip(
          //                             label: Text("已出单"),
          //                             avatar: Icon(Icons.radio_button_checked),
          //                             backgroundColor: Color(0xfff4978e),
          //                             labelStyle:
          //                                 TextStyle(color: Colors.black),
          //                           )
          //               ],
          //             ),
          //           ),
          //         ),
          //       ),
          //     );
          //   },
          // ),
        ),
      ),
    );
  }
}
